import axios from 'axios';
import store from '@/store/index.ts';
import { blob2Json } from '@/utils/common';
import { message } from '@/utils/resetMessage';

const isLocal = window.XCConfig.VITE_ENV === 'local';

const instance = axios.create({
    baseURL: window.XCConfig.VITE_URL,
    responseType: 'blob',
});
const getToken = () => {
    if (store.state.puma.token) {
        const { accessToken } = JSON.parse(store.state.puma.token);
        return accessToken || '';
    }
    return '';
};

instance.interceptors.request.use(
    (config) => {
        config.headers.Authorization = `Bearer ${getToken()}`;
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

instance.interceptors.response.use(async (response) => {
    console.log(response.headers['content-disposition']);
    // 当返回类型是二进制流时
    if (response.data instanceof Blob) {
        // blob转JSON，如果返回JSON,表示文件验证不通过，
        const { type, jsonData } = await blob2Json(response.data);
        if (type === 'blob') {
            return {
                file: response.data,
                fileName: decodeURIComponent(response.headers['content-disposition']?.split('fileName=')[1]) || '',
            };
        }
        message({
            message: jsonData.msg || jsonData.message || '系统异常',
            type: 'error',
            duration: 5 * 1000,
        });
        return Promise.reject();
    }
    message({
        message: response.data.msg || response.data.message || '系统异常',
        type: 'error',
        duration: 5 * 1000,
    });
    return Promise.reject();
});

export default instance;
